﻿using System;
using System.Text;
using System.Web.UI;
using System.Xml.Linq;

namespace SPAdaptiveMenu.Controls
{
    ///<summary>
    ///</summary>
    public class MenuPostBack : MenuOption, IPostBackEventHandler
    {
        ///<summary>
        ///</summary>
        public string CommandArgument { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if(Page.IsPostBack)
            {
                var target = Page.Request.Form["__EVENTTARGET"];
                if(target == UniqueID)
                {
                    var arg = new MenuItemEventArgs { Argument = Page.Request.Form["__EVENTARGUMENT"], Item = this };
                    OnClick(arg);
                }
                
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            var onclick = Page.ClientScript.GetPostBackEventReference(this, CommandArgument);
            var sb = new StringBuilder();

            sb.Append("<ie:menuitem");
            sb.AppendFormat(@" id=""{0}""", ClientID);
            sb.Append(@" type=""option""");

            sb.AppendFormat(@" onMenuClick=""{0}""", onclick);
            if (!string.IsNullOrEmpty(Title))
                sb.AppendFormat(@" title=""{0}""", Title);
            if (!string.IsNullOrEmpty(IconToolTip))
                sb.AppendFormat(@" iconAltText=""{0}""", IconToolTip);
            if (!string.IsNullOrEmpty(IconSrc))
                sb.AppendFormat(@" iconSrc=""{0}""", IconSrc);
            if (!string.IsNullOrEmpty(Description))
                sb.AppendFormat(@" description=""{0}""", Description);
            if (!string.IsNullOrEmpty(Title))
                sb.AppendFormat(@" text=""{0}""", Title);
            if (Disabled)
                sb.Append(@" enabled=""false""");
            if (Hidden)
                sb.Append(@" hidden=""true""");
            sb.Append("></ie:menuitem>");
            writer.Write(sb.ToString());
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            var e = new MenuItemEventArgs { Argument = eventArgument, Item = this };
            OnClick(e);
        }

        private EventHandler _click;
        public event EventHandler Click
        {
            add { _click += value; }
            remove { _click -= value; }
        }

        protected virtual void OnClick(MenuItemEventArgs e)
        {
            if (_click != null)
                _click(this, e);
        }
        
        protected internal override XElement Serialized
        {
            get
            {
                var element = base.Serialized;
                element.Attribute("Type").Value = ItemType.ToString();
                element.Add(new XAttribute("CommandArgument", CommandArgument ?? string.Empty));
                return element;
            }
        }

        protected override object SaveControlState()
        {
            base.SaveControlState();
            var obj = base.SaveControlState();
            return obj != null
                ? (object)new Pair(obj, Serialized.ToString())
                : Serialized.ToString();
        }

        protected override void LoadControlState(object state)
        {
            if (state == null) return;
            var p = state as Pair;
            if (p != null)
            {
                base.LoadControlState(p.First);
                InitProperties(XElement.Parse((string)p.Second));
            }
            else
            {
                if (state is string)
                    InitProperties(XElement.Parse((string)state));
                else
                    base.LoadControlState(state);
            }
        }

        protected internal override void InitProperties(XElement element)
        {
            if (element == null) return;
            base.InitProperties(element);
            CommandArgument = element.Attribute("CommandArgument").Value;
        }

        protected internal override XElement HTML
        {
            get
            {
                var element = base.HTML;
                var onclick = Serialized.Attribute("OnClickText").Value;
                element.Attribute("onMenuClick").Value = onclick;
                return element;
            }
        }
    }
}
